package com.jerry.boot.core.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jerry.boot.core.base.ApiException;
import com.jerry.boot.core.base.JConfigureProperties;
import com.jerry.boot.core.mvc.JsonResult;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public abstract class AbstractJFilter implements JFilter {

    private final MessageSource messageSource;

    private final ObjectMapper objectMapper;

    private final JConfigureProperties jConfigureProperties;

    protected AbstractJFilter(MessageSource messageSource, ObjectMapper objectMapper, JConfigureProperties jConfigureProperties) {
        this.messageSource = messageSource;
        this.objectMapper = objectMapper;
        this.jConfigureProperties = jConfigureProperties;
    }

    @Override
    public boolean deal(HttpServletRequest request, HttpServletResponse response) {
        try {
            execute(request, response);
            return true;
        } catch (ApiException e) {
            dealError(request, response, e);
        }
        return false;
    }

    protected void dealError(HttpServletRequest request, HttpServletResponse response, ApiException e) {
        if (e != null) {
            if (ServletContextHelper.isAjaxRequest(request)) {
                JsonResult jsonResult = JsonResult.create();
                try {
                    String message = messageSource.getMessage(e.getCode() + "", e.getArgs(), request.getLocale());
                    jsonResult.setCode(e.getCode());
                    jsonResult.setMsg(message);
                } catch (NoSuchMessageException ex) {
                    jsonResult.setCode(500);
                    jsonResult.setMsg(messageSource.getMessage("500", null, request.getLocale()));
                }
                try (PrintWriter writer = response.getWriter()) {
                    String str = objectMapper.writeValueAsString(jsonResult);
                    writer.write(str);
                    writer.flush();
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            } else {
                try {
                    response.sendRedirect(jConfigureProperties.getLoginUrl());
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }
        }
    }

    public abstract void execute(HttpServletRequest request, HttpServletResponse response) throws ApiException;


}
